#include <transactionProducer.h>
#include <phpSendResult.h>

void TransactionProducer::__construct(Php::Parameters &params)
{
}

void TransactionProducer::__destruct()
{
    transactionProducer->shutdown();
}

void TransactionProducer::start()
{
    transactionProducer->start();
}

void TransactionProducer::setProducerGroup(Php::Parameters &params)
{
    if (params.size() != 1) {
        throw Php::Exception("Incorrect number of parameters assigned.");
    }

    transactionProducer->setProducerGroup(params[0].stringValue());
}

void TransactionProducer::endTransaction(Php::Parameters &params)
{
    if (params.size() != 2) {
        throw Php::Exception("Incorrect number of parameters assigned.");
    }

    std::string msgId = params[0].stringValue();
    if(msgId == "" || msgId != sendResult.getMsgId()) {
        throw Php::Exception("请先调用sendMessageInTransaction.");
    }

    LocalTransactionState localTransactionState;
    switch((int16_t) params[1]) {
        case 0:
            localTransactionState = COMMIT_MESSAGE;
            break;
        case 1:
            localTransactionState = ROLLBACK_MESSAGE;
            break;
        case 2:
            localTransactionState = UNKNOW;
            break;
        default:
            throw Php::Exception("无效的事务执行状态" + params[1].stringValue());
            break;
    }

    transactionProducer->endTransaction(sendResult, localTransactionState);
}

Php::Value TransactionProducer::sendMessageInTransaction(Php::Parameters &params) {
    if (params.size() != 4) {
        throw Php::Exception("Incorrect number of parameters assigned.");
    }

    std::string value(params[3].stringValue());

    Message msg(params[0].stringValue(),// topic
                        params[1].stringValue(),// tag
                        params[2].stringValue(),// key
                        value.c_str(),// body
                        value.size());

    try {
	   sendResult = transactionProducer->sendMessageInTransaction(msg);
    }
    catch(MQClientException e) {
        throw Php::Exception(e.what());
    }

    PhpSendResult *phpSendResult = new PhpSendResult(sendResult);
    Php::Value result = Php::Object("PhpSendResult", phpSendResult);

    return result;
}
